//
//  CoreDataManager.m
//  Droplets
//
//  Created by 米明 on 15/2/9.
//  Copyright (c) 2015年 米明. All rights reserved.
//

#import "CoreDataManager.h"


static CoreDataManager * manager = nil;

@implementation CoreDataManager

+(CoreDataManager *)shareManager{
    
    @synchronized(self) {
        
        if(!manager) {
            
           manager =  [[self alloc] init];
            
        }
        return manager;
    }
}
+ (id) allocWithZone:(NSZone *)zone{
    @synchronized (self) {
        if (manager == nil) {
            manager = [super allocWithZone:zone];
            return manager;
        }
    }
    return nil;
}
- (id) copyWithZone:(NSZone *)zone 
{
    return self;
}

#pragma mark - 保存上下文
- (void)saveContext
{
    NSError *error =nil;
    NSManagedObjectContext * managedObjectContext =self.objcContext;
    
    if (managedObjectContext !=nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
           // NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }else{
           // NSLog( @"数据成功插入");
        }
    }
}
#pragma mark - 获取Application's Documents directory url
- (NSURL *)applicationDocumentsDirectory{
    
    NSURL *url=[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    //NSLog(@"%@",url);
    //NSFileManager *file=[NSFileManager defaultManager];
    //NSLog(@"%@",file);
    
    //NSLog(@"%@",[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]);
    return url;
}
#pragma mark - 持久化数据存储协调器
-(NSPersistentStoreCoordinator *)persistentStoreCoordinator{
    
    NSLog(@"数据存储协调器");
    if (self.coordinator !=nil) {
        return self.coordinator;
    }
    
    NSURL *storeURL = [[self applicationDocumentsDirectory]URLByAppendingPathComponent:@"CoreData.sqlite"];//数据库的名字
   
    NSLog(@"%@",storeURL);
    
    NSError *error =nil;
    self.coordinator = [[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:[self managedObjectModel]];
    
    if (![self.coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    return self.coordinator;
}
#pragma mark - 对象模型
- (NSManagedObjectModel *)managedObjectModel
{
    NSLog(@"对象模型");
    if (self.objcModel !=nil) {
        return self.objcModel;
    }
    
    NSURL *modelURL = [[NSBundle mainBundle]URLForResource:@"CoreData" withExtension:@"momd"];
    self.objcModel = [[NSManagedObjectModel alloc]initWithContentsOfURL:modelURL];
    
    return self.objcModel ;
}
#pragma mark - 初始化上下文
- (NSManagedObjectContext *)managedObjectContext
{
    NSLog(@"上下文");
    if (self.objcContext !=nil) {
        return self.objcContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator !=nil) {
        self.objcContext = [[NSManagedObjectContext alloc]init];
        [self.objcContext setPersistentStoreCoordinator:coordinator];
    }
    return self.objcContext;
}


#pragma mark - 初始化
-(instancetype)init{
    
    self=[super init];
    if (self) {
        
        NSLog(@"初始化数据库");
        self.objcModel=[self managedObjectModel];
        
        self.coordinator=[self persistentStoreCoordinator];
      
        self.objcContext=[self managedObjectContext];
        
    }
    return self;
}


#pragma mark - 删除对象
-(void)deleteObjectModel:(NSManagedObject *)model{
    
    [self.objcContext deleteObject:model];
    NSLog(@"数据库删除");
    NSError *error =nil;
    if (![self.objcContext save:&error]) {
        //handle error
         NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    }
}
#pragma mark - 查询对象
-(NSArray *)getModels:(NSString *)objcName{
    
    NSFetchRequest * request=[[NSFetchRequest alloc]init];
    
    NSEntityDescription * myEntityQuery=[NSEntityDescription entityForName:objcName inManagedObjectContext:self.objcContext];
    
    [request setEntity:myEntityQuery];
    
    NSString * key;
    if ([objcName isEqualToString:@"Task"]) {
        key=@"photoPath";
    }else if ([objcName isEqualToString:@"UpGoods"]){
        key=@"goodsId";
    }
    
    NSSortDescriptor * sortDescriptor=[[NSSortDescriptor alloc]initWithKey:key ascending:NO];
    
    NSArray * sortDesctpors=[[NSArray alloc]initWithObjects:sortDescriptor, nil];
    
    [request setSortDescriptors:sortDesctpors];
    
    NSError * error=nil;
    
    NSArray * arr=[self.objcContext executeFetchRequest:request error:&error];

    
    return arr;
}
-(BOOL)isHasGoodsByGoodsId:(NSString *)goodsId{
    if (goodsId) {
        for (UpGoods * goodsObj in [self getModels:@"UpGoods"]) {
            if ([goodsId isEqualToString:goodsObj.goodsId]) {
                return YES;
            }
        }
    }
    return NO;
}
-(void)addGoods:(Goods *)goods{
    if ([self isHasGoodsByGoodsId:goods.Id]) {
        return;
    }
    NSManagedObjectContext * objcContext=[[CoreDataManager shareManager]managedObjectContext];
    
    UpGoods * goodsObj =[NSEntityDescription insertNewObjectForEntityForName:@"UpGoods"
                                                 inManagedObjectContext:objcContext];
    //属性赋值
    goodsObj.goodsId=goods.Id;
    goodsObj.goodsName=goods.name;
    goodsObj.code = goods.code;
    // 保存数据，持久化存储 SQLite数据库
    
    [[CoreDataManager shareManager] saveContext];
}
-(void)deleteGoods:(Goods *)goods{
    for (UpGoods * goodsObj in [self getModels:@"UpGoods"]) {
        if ([goods.Id isEqualToString:goodsObj.goodsId]) {
            [[CoreDataManager shareManager]deleteObjectModel:goodsObj];
        }
    }
    
    [[CoreDataManager shareManager]saveContext];
}
-(void)clearGoods{
    
    NSArray * objs = [self getModels:@"UpGoods"];
    
    for (UpGoods * goodsObj in objs) {
        
        [[CoreDataManager shareManager]deleteObjectModel:goodsObj];
        
    }
    
    [[CoreDataManager shareManager]saveContext];
}
-(void)addTask:(UploadTask *)task{
    
    if ([self isHasTaskByPhotoPath:task.photoPath]) {
        return;
    }
    NSManagedObjectContext * objcContext=[[CoreDataManager shareManager]managedObjectContext];
    
    Task *taskObj =[NSEntityDescription insertNewObjectForEntityForName:@"Task"
                                                        inManagedObjectContext:objcContext];
    //属性赋值
    taskObj.goodsId=task.goods.Id;
    taskObj.photoPath=task.photoPath;
    taskObj.isDone=@(NO);
    taskObj.name = [NSString stringWithFormat:@"%d",(int)task.number];
    taskObj.photoName=task.photoPath;
    // 保存数据，持久化存储 SQLite数据库
    
    [[CoreDataManager shareManager] saveContext];
}
-(void)deleteTaskByPhotoPath:(NSString *)photoPath{
    for (Task * taskObj in [self getModels:@"Task"]) {
        if ([photoPath isEqualToString:taskObj.photoPath]) {
            [[CoreDataManager shareManager]deleteObjectModel:taskObj];
        }
    }
    
    [[CoreDataManager shareManager]saveContext];
}
-(void)deleteAllTask{
    for (Task * taskObj in [self getModels:@"Task"]) {
        
        [[CoreDataManager shareManager]deleteObjectModel:taskObj];
        
    }
    [[CoreDataManager shareManager]saveContext];
}
-(void)deleteDoneTask{
    for (Task * taskObj in [self getModels:@"Task"]) {
        
        if (taskObj.isDone) {
            [[CoreDataManager shareManager]deleteObjectModel:taskObj];
        }
    }
    [[CoreDataManager shareManager]saveContext];
    
}
-(void)taskDoneWithPhotoPath:(NSString *)photoPath{
    if ([self isHasTaskByPhotoPath:photoPath]) {
        for (Task * taskObj in [self getModels:@"Task"]) {
            if ([photoPath isEqualToString:taskObj.photoPath]) {
                taskObj.isDone = @(YES);
            }
        }
    }
    [[CoreDataManager shareManager]saveContext];
}
-(int)maxNumberWithGoodsId:(NSString *)goodsId{
    if (goodsId) {
       
        int number =0;
        for (Task * taskObj in [self getModels:@"Task"]) {
            if ([goodsId isEqualToString:taskObj.goodsId]) {
                NSLog(@"index %@",taskObj.name);
                if ([taskObj.name intValue]>number) {
                    number = [taskObj.name intValue];
                }
            
            }
        }
        return number%1000;
    }
    return 0;
}
-(NSMutableArray *)tasks{
    
    NSArray * objcArr=[[CoreDataManager shareManager]getModels:@"Task"];
    
    NSMutableArray * arr= [[NSMutableArray alloc]init];
    
    int count = 0;
    
    for (Task * task in objcArr) {
        Goods * goods=[[Goods alloc]init];
        goods.Id = task.goodsId;
        UploadTask * upTask =[[UploadTask alloc]initWithPhotoPath:task.photoPath goods:goods];
        upTask.number=[task.name integerValue];
        [arr addObject:upTask];
        count++;
        if (count>2000) {
            return arr;
        }
    }
    return arr;
}
-(NSMutableArray *)goodsList{
    
    NSArray * objcArr=[[CoreDataManager shareManager]getModels:@"UpGoods"];
    
    NSMutableArray * arr= [[NSMutableArray alloc]init];
    
    for (UpGoods * goodsObj in objcArr) {
        Goods * goods=[[Goods alloc]init];
        goods.Id = goodsObj.goodsId;
        goods.name = goodsObj.goodsName;
        goods.code=goodsObj.code;
        [arr addObject:goods];
    }
    return arr;
    
}

-(BOOL)isHasTaskByPhotoPath:(NSString *)photoPath{
    if (photoPath) {
        for (Task * taskObj in [self getModels:@"Task"]) {
            if ([photoPath isEqualToString:taskObj.photoPath]) {
                return YES;
            }
        }
    }
    return NO;
}


@end
